<template>
  <div class="address">
    <el-input class="input" v-if="!textArea" v-model="addressName"  :readonly="true" :disabled="inputDisabled" v-on:click.native="showAddressPanel" suffix-icon="el-icon-user-solid" style="width:96.5%"/>
    <el-input class="input" v-if="textArea" type="textarea" v-model="addressName"  :readonly="true" :disabled="inputDisabled" v-on:click.native="showAddressPanel" suffix-icon="el-icon-user-solid" style="width:96.5%"/>
    <el-dialog v-dialogDrag class="dialog" :title="title" center :visible.sync="visible" width="830px" :show-close="false">
          <el-row>
            <el-col :span="8">
              <el-scrollbar class="scroll-tree" style="width:250px;">
                <!--左侧树-->
                <el-tree
                  :props="props"
                  :load="loadNode"
                  lazy
                  :highlight-current="true"
                  :expand-on-click-node="false"
                  @node-click="handleNodeClick">
                  <span class="custom-tree-node" slot-scope="{ node,data }">
                    <svg class="icon" aria-hidden="true" v-if="data.orgType ==1">
                      <use xlink:href="#icon-org"></use>
                    </svg>
                    <svg class="icon" aria-hidden="true" v-if="data.orgType ==2">
                      <use xlink:href="#icon-dept"></use>
                    </svg>
                    <svg class="icon" aria-hidden="true" v-if="data.orgType ==3">
                      <use xlink:href="#icon-post"></use>
                    </svg>
                    <svg class="icon" aria-hidden="true" v-if="data.orgType ==4">
                      <use xlink:href="#icon-person2"></use>
                    </svg>
                    <span style="margin-left:5px">{{ node.label }}</span>
                  </span>
                </el-tree>
              </el-scrollbar>
            </el-col>
            <el-col :span="7" >
              <!-- <div class="source-header ">待选择</div> -->
              <el-scrollbar class="scroll-tree" style="width:220px">
              <el-table
                :data="sourceList"
                :highlight-current-row="!multi"
                :show-header="true"
                @row-click = "handleRowClick"
                @select-all= "handleSelectAll"
                @select = "handleSelect"
                ref="multipleTable"
                style="width: 100%">
                  <el-table-column type="selection" width="30" v-if="multi"></el-table-column>
                  <el-table-column
                    :sortable="true"
                    prop="name"
                    align="center"
                    label="待选择">
                  </el-table-column>
              </el-table>
              </el-scrollbar>
            </el-col>
            <el-col :span="2">
              <div style="margin-top:150px;margin-left:25px">
                <center>
                  <el-button type="primary" icon="el-icon-right" plain circle 
                    :disabled="hasBuffer" style="margin-top:20px;"
                    @click="handleChangeBufferItemToTargetList"
                    ></el-button>
                </center>
              </div>
            </el-col>
            <el-col :span="7" style="margin-left:-1px">
              <!-- <div class="source-header">已选择</div> -->
              <el-scrollbar class="scroll-tree" style="width:220px">
              <el-table
                :data="targetList"
                :show-header="true"
                style="width: 100%">
                  <el-table-column 
                    prop="name"
                    align="center"
                    label="待选择"
                  >
                  </el-table-column>
                  <el-table-column width="50">
                    <template slot-scope="scope">
                      <div class="target-column">
                        <i class="el-icon-lx-delete delete-icon"
                      @click="handlTargetItemDelete(scope.$index, scope.row)"
                      ></i>
                      </div>
                    </template>
                  </el-table-column>
              </el-table>
              </el-scrollbar>
            </el-col>
          </el-row>
          
          <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="handlerConfirm">确 定</el-button>
              <el-button @click="visible = false">取 消</el-button>
          </span>
      </el-dialog>
  </div>
</template>
<script>
//简单地址本,左侧树,右侧选择人,暂时不考虑岗位
  export default {
    name: "fancyAddress",
    data() {
      return {
        version:'1.0',
        title:'地址本',
        props: {
          label: 'name'
        },
        addressId:'',
        addressName:'',
        visible:false,
        sourceList: [],
        targetList: [],
        bufferList:[] //选中的列表
      }
    },
    /**
     * 暂时只考虑机构
     * 参数:
     * multi:是否多选
     * 
     */

    props:{
      multi: { 
        type: Boolean,
        default:false
      },
      textArea: { 
        type: Boolean,
        default:false
      },
      id: {
        type: String,
        default: ""
      },
      value: {
        type: String
      },
      showStatus: {
        type: String,
        default: "edit"  //edit,view,暂时不支持其他
      }
      ,
      orgType: {
        type: String,
        default: "ORG|DEPT|PERSON"//可以选择的类型,但是目前只支持单选"ORG|DEPT|POST|PERSON"
      }
    },
    methods: {
      showAddressPanel() {
        if(this.showStatus !== 'edit') return;
        this.visible = true;
        if(this.addressId!== ''){
          if(this.$props.multi){
            const idArray = this.addressId.split(';');
            const nameArray = this.addressName.split(';');
            this.targetList = [];
            idArray.forEach((item,index)=>{
              let obj = {
                id:item,
                name:nameArray[index]
              }
              this.targetList.push(obj);
            })
          }else{
            let obj = {
              id:this.addressId,
              name:this.addressName
            }
            this.targetList = [];
            this.targetList.push(obj);
          }
        }
      },
      
      handleNodeClick(data) {
        this.getListData(data,(d)=>{
          this.sourceList = [];
          d.forEach((value,index)=>{
            let obj = {
              id:value.id,
              name:value.name
            }
            this.sourceList.push(obj);
          })
        });
      },
      loadNode(node, resolve) {
        if (node.level === 0) {
          this.getTreeData("",(data)=>resolve([{"id":"","name":"组织架构",orgType:""}]));
        } else {
          this.getTreeData(node.data,(data)=>resolve(data));
        }
      },
      getListData(data,callback){
        let params = {
          fdParentId:data.id,
          fdParentType:data.orgType,
          fdOrgType:this.$props.orgType
        }
        this.$fetch('/api/sys/org/sys_org_element/listData',params).then((res) => {
          if(res.status==1){
            return callback(res.data);
          }
        });
      },
      getTreeData(data,callback){
        let params = {
          fdParentId:data.id,
          fdParentType:data.orgType,
          fdOrgType:this.$props.orgType
        }
        this.$fetch('/api/sys/org/sys_org_element/treeData',params).then((res) => {
          if(res.status==1){
            return callback(res.data);
          }
        });
      },
      handlTargetItemDelete(index,row){
        this.targetList.splice(index,1);
      },
      handleChangeBufferItemToTargetList() {
        this.bufferList.forEach((item,index)=>{
          if(this.$props.multi){
            if(!this.contains(this.targetList,item)){
                this.targetList.push(item);
            } 
          }else{
            if(!this.contains(this.targetList,item)){
                this.targetList = [];
                this.targetList.push(item);
            } 
          }
        })
        this.bufferList = [];
      },
      contains(arr,obj) {
        let i = arr.length;
        while (i--) {
            if (arr[i].id === obj.id) {
                return true;
            }
        }
        return false;
      },
      handleRowClick(row){
        if(this.$props.multi){
          let checkList = this.$refs.multipleTable.selection;
          if(checkList.length==0){
            this.$refs.multipleTable.toggleRowSelection(row,true);
            this.bufferList.push(row);
          }else{
            if(!this.contains(checkList,row)){//当前未选中
              this.$refs.multipleTable.toggleRowSelection(row,true);
              this.bufferList.push(row);
            }else{
              this.$refs.multipleTable.toggleRowSelection(row,false);
              const index = this.bufferList.findIndex(item => item.id === row.id);
              this.bufferList.splice(index, 1);
            }
            
          }
        }else{
          if(this.bufferList.length>0){
            this.bufferList = [];
          }
          this.bufferList.push(row);
        }
      },
      handleSelectAll(selection) {
        if(selection.length>0){
          selection.forEach((item,index)=>{
            if(!this.contains(this.bufferList,item)){
              this.bufferList.push(item)
            }
          });
        }else{
          this.bufferList = [];
        }
      },
      handleSelect(selection,row) {
        if(selection.length>0){
          selection.forEach((item,index)=>{
            if(!this.contains(this.bufferList,item)){
              this.bufferList.push(item)
            }
          });
        }else{
          this.bufferList.splice(this.bufferList.findIndex(item => item.id === row.id), 1);
        }
      },
      handlerConfirm(){
        if(this.$props.multi){
          if(this.targetList.length>0){
            let row = this.targetList;
            const idsArray = row.map(v=>v.id);
            const namesArray = row.map(v=>v.name);
            this.$emit('update:id',idsArray.join(';')); 
            this.addressName = namesArray.join(';');
            this.$emit('input', this.addressName);
            this.$emit('onValueChange',this.targetList); 
          }else{
            this.$emit('update:id',''); 
            this.addressName = '';
            this.$emit('input', '')
            this.$emit('onValueChange',{}); 
          }
        }else{
          if(this.targetList.length>0){
            let row = this.targetList[0];
            this.$emit('update:id',row.id); 
            //this.value= row.name;
            //this.$emit('update:name',row.name);
            this.addressName = row.name;
            this.$emit('input', row.name);
            this.$emit('onValueChange',row); 
          }else{
            this.$emit('update:id',''); 
            //this.value= row.name;
            //this.$emit('update:name',row.name);
            this.addressName = '';
            this.$emit('input', '')
            this.$emit('onValueChange',{}); 
          }
        }
        
        this.sourceList = [];
        this.bufferList = [];
        this.targetList = [];
        this.visible = false;
      }
    },
    computed:{
      hasBuffer : function(){
        //if(this.multi) return false;
        return this.bufferList.length<1;
      },
      inputDisabled:function() {
        return this.showStatus === 'edit'?false:true;
      }
    },
    watch: {
      id(newName,oldName) {
        this.addressId = newName;
        this.addressName = this.value;
      }
    }
  }
</script>

<style scoped>

/* .el-dialog__header{
  padding-top:5px;
  padding-bottom:5px;
  background-color: #F5F7FA
} */
.el-transfer__buttons{
  padding: 0 20px
}
.el-transfer-panel{
  height:400px
}
.scroll-tree{
  height:400px;
  float:left;
}
.scroll-tree >>>.el-scrollbar__wrap{
  overflow-x:hidden;
}
.source-header{
  width:250px;
  height:30px;
  background-color:#F5F7FA;
  text-align: center;
}
.target-column{
  margin-left: 10px;
}
.delete-icon:hover{
  cursor:pointer
}
</style>